package com.qf.service;

import com.qf.dao.AccountDaoImpl;
import com.qf.entity.Account;
import com.qf.utils.DruidUtil;

/*
杨威
2021/9/6
20:17
*/
public class AccountServiceImpl {
    public  void transfer(String fromCardNum,String fromPassWord,Integer money,String toCardNum){
        AccountDaoImpl accountDao=new AccountDaoImpl();
        //1查询转账方卡号是否存在dao
        try {
            DruidUtil.begin();
            Account fromAccount = accountDao.select(fromCardNum);
            System.out.println("fromAccount = " + fromAccount);
            if(fromAccount==null){
                throw new RuntimeException("卡号不存在");
            }
            //2查询密码
            if(!fromPassWord.equals(fromAccount.getPassWord())){
                throw new RuntimeException("密码错误");
            }
            //3查询余额
            if(fromAccount.getBalance()<money){
                throw new RuntimeException("余额不足");
            }
            //4查询对方卡号是否存在dao
            Account toAccount = accountDao.select(toCardNum);
            if(toAccount==null){
                throw new RuntimeException("对方卡号不存在");
            }
            //5转账方扣钱dao

            fromAccount.setCardNum(fromCardNum);
            fromAccount.setBalance(fromAccount.getBalance()-money);
            accountDao.update(fromAccount);
//            int i=10/0;
            //6对方账号加钱dao
            toAccount.setCardNum(toCardNum);
            toAccount.setBalance(toAccount.getBalance()+money);
            accountDao.update(toAccount);
            System.out.println("转账成功");
            DruidUtil.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                System.out.println("转账失败");
                DruidUtil.rollback();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }finally {

        }
    }


}
